/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import com.MHSoftware.net.IP.*;
import com.codemagi.util.Utils;
import java.io.IOException;
import javax.servlet.*;
import org.apache.log4j.Logger;

/**
 * Filter incoming requests based on IP Address. 
 *
 * Incoming requests will only be allowed if they fall within the specified IP address / netmask. 
 * All other requests will be forwarded to /access_denied.jsp
 *
 * @todo   Make access denied URL configurable
 *
 * @version 1.0
 * @author August Detlefsen for CodeMagi, Inc.
 */
public final class IpAddressAllowFilter implements Filter {

    //setup logging
    Logger log = Logger.getLogger(this.getClass());

    private FilterConfig config = null;

    private String ipAddress  = "";
    private String netMask    = "255.255.255.255";

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;

	ipAddress   = config.getInitParameter("ipAddress");
	if (Utils.isEmpty(ipAddress)) throw new ServletException("Unable to instantiate IpAddressFilter: ipAddress not specified");
	
	if (!Utils.isEmpty(config.getInitParameter("netMask")) )
	    netMask = config.getInitParameter("netMask");
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	String remoteIpAddress = request.getRemoteAddr();

	if ( !IpAddress.isAddressInNetwork(remoteIpAddress, ipAddress, netMask) ) {
	    log.fatal("ERROR: Attempt to access restricted resource from IP: " + remoteIpAddress);
	    RequestDispatcher dispatcher = config.getServletContext().getRequestDispatcher(BaseServlet.VIEW_ACCESS_DENIED);
	    dispatcher.forward(request, response);
	    return;

	} else {
	    chain.doFilter(request, response);
	}

    }
}
